Jackson এর মাধ্যমে JSON Schema Validation করা

Java Technologies - জ্যাকসন (Jackson) - JSON Schema Validation
196

Jackson লাইব্রেরি JSON ডেটার সাথে কাজ করার জন্য অসাধারণ একটি টুল। JSON Schema Validation একটি গুরুত্বপূর্ণ ফিচার, যা নিশ্চিত করে যে JSON ডেটা নির্দিষ্ট একটি স্কিমার (structure, type, constraints) সাথে সামঞ্জস্যপূর্ণ।

Jackson ব্যবহার করে JSON Schema Validation করতে json-schema-validator মডিউল ব্যবহৃত হয়। এটি Jackson এবং JSON Schema Draft-4/7/2020 সমর্থন করে।


JSON Schema Validation সেটআপ

প্রয়োজনীয় Maven ডিপেনডেন্সি:

<dependency>
    <groupId>com.github.java-json-tools</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.2.14</version> <!-- সর্বশেষ ভার্সন -->
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Jackson এর জন্য -->
</dependency>

Step-by-Step JSON Schema Validation উদাহরণ

১. JSON Schema তৈরি করা

JSON Schema একটি স্ট্যান্ডার্ড ফরম্যাট যা ডেটার কাঠামো এবং কন্ট্রেইন্ট নির্ধারণ করে।

Example Schema (user-schema.json):

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "User",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1
    },
    "age": {
      "type": "integer",
      "minimum": 0
    },
    "email": {
      "type": "string",
      "format": "email"
    }
  },
  "required": ["name", "age"]
}

২. JSON ডেটা প্রস্তুত করা

{
  "name": "Alice",
  "age": 25,
  "email": "alice@example.com"
}

৩. Jackson এবং json-schema-validator ব্যবহার করে Validation

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonSchema;

import java.io.File;
import java.io.IOException;

public class JsonSchemaValidationExample {
    public static void main(String[] args) {
        try {
            // ObjectMapper তৈরি
            ObjectMapper mapper = new ObjectMapper();

            // JSON Schema এবং JSON ডেটা লোড করা
            JsonNode schemaNode = mapper.readTree(new File("user-schema.json"));
            JsonNode dataNode = mapper.readTree(new File("user-data.json"));

            // JSON SchemaFactory তৈরি
            JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
            JsonSchema schema = factory.getJsonSchema(schemaNode);

            // Validation প্রক্রিয়া
            ProcessingReport report = schema.validate(dataNode);

            // Validation রিপোর্ট প্রিন্ট করা
            if (report.isSuccess()) {
                System.out.println("JSON is valid.");
            } else {
                System.out.println("JSON is invalid.");
                System.out.println(report);
            }
        } catch (IOException | ProcessingException e) {
            e.printStackTrace();
        }
    }
}

আউটপুট

Valid JSON:

JSON is valid.

Invalid JSON:

Input JSON:

{
  "name": "",
  "age": -5
}

Output:

JSON is invalid.
--- BEGIN MESSAGES ---
error: string [\"\"] is too short
    level: "error"
    schema: {...}
    instance: {...}

error: number [-5] is less than the minimum of 0
    level: "error"
    schema: {...}
    instance: {...}
--- END MESSAGES ---

৪. Runtime Schema Validation

JSON Schema ফাইল ছাড়াই প্রোগ্রামটিকভাবে স্কিমা তৈরি করা সম্ভব।

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonSchema;

public class RuntimeSchemaValidationExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // JSON Schema প্রোগ্রামটিকভাবে তৈরি
        String schemaString = """
                {
                  "$schema": "http://json-schema.org/draft-07/schema#",
                  "type": "object",
                  "properties": {
                    "name": {"type": "string", "minLength": 1},
                    "age": {"type": "integer", "minimum": 0}
                  },
                  "required": ["name", "age"]
                }
                """;
        JsonNode schemaNode = mapper.readTree(schemaString);

        // JSON ডেটা
        String jsonString = """
                {
                  "name": "Alice",
                  "age": 25
                }
                """;
        JsonNode dataNode = mapper.readTree(jsonString);

        // JSON Schema Validation
        JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
        JsonSchema schema = factory.getJsonSchema(schemaNode);

        ProcessingReport report = schema.validate(dataNode);

        if (report.isSuccess()) {
            System.out.println("JSON is valid.");
        } else {
            System.out.println("JSON is invalid.");
            System.out.println(report);
        }
    }
}

৫. Spring Boot এ JSON Schema Validation

Spring Boot এর REST API তে JSON Schema Validation সহজে সংযুক্ত করা যায়।

Controller:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonSchema;

import java.io.IOException;

@RestController
@RequestMapping("/api/validate")
public class SchemaValidationController {

    @PostMapping
    public ResponseEntity<String> validateJson(@RequestBody String jsonData) {
        try {
            ObjectMapper mapper = new ObjectMapper();

            // JSON Schema লোড করা
            JsonNode schemaNode = mapper.readTree(new File("user-schema.json"));

            // JSON Data লোড করা
            JsonNode dataNode = mapper.readTree(jsonData);

            // Validation
            JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
            JsonSchema schema = factory.getJsonSchema(schemaNode);

            ProcessingReport report = schema.validate(dataNode);

            if (report.isSuccess()) {
                return ResponseEntity.ok("JSON is valid.");
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid JSON:\n" + report.toString());
            }
        } catch (IOException | com.github.fge.jsonschema.core.exceptions.ProcessingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage());
        }
    }
}

API Call:

  • Request (Valid):
{
  "name": "Bob",
  "age": 30
}
  • Response:
"JSON is valid."
  • Request (Invalid):
{
  "name": "",
  "age": -1
}
  • Response:
"Invalid JSON:
error: string [\"\"] is too short
error: number [-1] is less than the minimum of 0"

  • Jackson এর মাধ্যমে JSON Schema Validation করা সম্ভব json-schema-validator লাইব্রেরি ব্যবহার করে।
  • এটি API ডেভেলপমেন্টে JSON ডেটার গুণমান নিশ্চিত করার একটি অত্যন্ত কার্যকর পদ্ধতি।
  • Spring Boot এর সাথে সহজেই ইন্টিগ্রেট করে REST API তে স্কিমা ভিত্তিক ভ্যালিডেশন প্রয়োগ করা যায়।
Content added By
Promotion
NEW SATT AI এখন আপনাকে সাহায্য করতে পারে।

Are you sure to start over?

Loading...